package com.duolaibei.business.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.duolaibei.business.R;
import com.duolaibei.business.api.ApiName;
import com.duolaibei.business.base.BaseActivity;
import com.duolaibei.business.config.Preferences;
import com.duolaibei.business.http.HttpUtils;
import com.duolaibei.business.model.ResponseResult;
import com.duolaibei.business.model.TerminalData;
import com.duolaibei.business.utils.ACache;
import com.duolaibei.business.utils.CommonUtil;
import com.duolaibei.business.utils.GsonUtil;
import com.duolaibei.business.utils.PreferenceUtil;
import com.duolaibei.business.utils.inject.Inject;
import com.duolaibei.business.view.App;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xlm on 2017/11/8 0008
 */

public class TerminalManageActivity extends BaseActivity {


    @Inject(R.id.search_add)
    private LinearLayout mLayoutSearchAdd;

    @Inject(R.id.reset)
    private RelativeLayout mLayoutReset;
    @Inject(R.id.search)
    private RelativeLayout mLayoutSearch;

    @Inject(R.id.add)
    private RelativeLayout mLayoutAdd;
    @Inject(R.id.back)
    private RelativeLayout mLayoutBack;
    @Inject(R.id.title)
    private TextView mViewTitle;
    @Inject(R.id.termimal_refresh)
    private SmartRefreshLayout mRefreshLayout;
    @Inject(R.id.termimal_recycle)
    private RecyclerView mRecyclerView;
    private CommonAdapter<TerminalData.DataBeanX.DataBean> mCommonAdapter;
    private List<TerminalData.DataBeanX.DataBean> mBeanList;
    private int pagesize = 5;
    private int pagenum = 1;

    private static final int MODE_QUERY = 1;
    private static final int MODE_REFRESH = 2;
    private static final int MODE_MORE = 3;

    private static int CURRENT_MODE = MODE_QUERY;

    private static int EDITOR_CODE = 1;

    private static int SEARCH_CODE = 2;
    private static int ADD_CODE = 3;

    private List<TerminalData.DataBeanX.DataBean> mShopListNew;

    private String type;
    private String shopId;
    private String terminal_name;
    private String terminal_id;

    private boolean isEdit = false;

    @Override
    protected void onGetIntent(Intent intent) {
        super.onGetIntent(intent);
        if (intent != null) {
            type = intent.getStringExtra("type");
        }
    }

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_terminal_manage);
    }

    @Override
    protected void initViews() {
        mViewTitle.setText("终端管理");
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        if ("all".equals(type)) {
            getTerminalData();
            mLayoutSearchAdd.setVisibility(View.VISIBLE);
            mLayoutReset.setVisibility(View.GONE);//重置
        }
        setTerminalAdapter();
    }

    @Override
    protected void onSetListener() {
        mLayoutSearch.setOnClickListener(this);
        mLayoutAdd.setOnClickListener(this);
        mLayoutBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                onRefreshData();
            }
        });
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (mShopListNew.size() == pagesize) {
                    pagenum++;
                    CURRENT_MODE = MODE_MORE;
                    getTerminalData();
                } else {
                    mRefreshLayout.setEnableLoadmore(false);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (R.id.search == v.getId()) {
            //查找
            Intent intent = new Intent(getThis(), SearchTerminalActivity.class);
            startActivityForResult(intent, SEARCH_CODE);
        } else if (R.id.add == v.getId()) {
            //新增
            Intent intent = new Intent(getThis(), TerminalEditorActivity.class);
            intent.putExtra("type", "add");
            startActivityForResult(intent, ADD_CODE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (SEARCH_CODE == requestCode) {
                //搜索
                shopId = data.getStringExtra("shop_id");
                terminal_name = data.getStringExtra("terminal_name");
                terminal_id = data.getStringExtra("terminal_id");
                type = "part";
                pagesize = 5;
                pagenum = 1;
                getTerminalData();
                mLayoutSearchAdd.setVisibility(View.GONE);
                mLayoutReset.setVisibility(View.VISIBLE);//重置
                mLayoutReset.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        type = "all";
                        mLayoutSearchAdd.setVisibility(View.VISIBLE);
                        mLayoutReset.setVisibility(View.GONE);//重置
                        onRefreshData();
                    }
                });
            } else if (ADD_CODE == requestCode) {
                //增加
                type = "all";
                onRefreshData();
                mLayoutSearchAdd.setVisibility(View.VISIBLE);
                mLayoutReset.setVisibility(View.GONE);//重置
            } else if (EDITOR_CODE == requestCode) {
                // 编辑
                onRefreshData();
                //搜索
//                shopId = data.getStringExtra("shop_id");
                terminal_name = data.getStringExtra("terminal_name");
                if ("all".equals(type)) {
                    mLayoutSearchAdd.setVisibility(View.VISIBLE);
                    mLayoutReset.setVisibility(View.GONE);//重置
                }
            }
        }
    }

    /**
     * 刷新列表界面
     */
    private void onRefreshData() {
        pagenum = 1;
        CURRENT_MODE = MODE_REFRESH;
        getTerminalData();
    }

    /**
     * 设置adapter
     */
    private void setTerminalAdapter() {
        mBeanList = new ArrayList<>();
        mCommonAdapter = new CommonAdapter<TerminalData.DataBeanX.DataBean>(getThis(),
                R.layout.item_terminal_manage,
                mBeanList) {
            @Override
            protected void convert(ViewHolder holder, final TerminalData.DataBeanX.DataBean dataBean, int position) {
                holder.setText(R.id.shop_name, String.valueOf(dataBean.getShop_name()));
                holder.setText(R.id.terminal_num, String.format(getString(R.string.item_terminal_s1), dataBean.getId()));
                holder.setText(R.id.terminal_name, String.format(getString(R.string.item_terminal_s2), dataBean.getName()));
                holder.setText(R.id.pos_num, String.format(getString(R.string.item_terminal_s3), dataBean.getDevice_pos()));
                holder.setText(R.id.print_num, String.format(getString(R.string.item_terminal_s4), dataBean.getDevice_print()));
                holder.setText(R.id.cashier, String.format(getString(R.string.item_terminal_s5), dataBean.getWorkmen_uid()));
                holder.getView(R.id.terminal_qrcode).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(getThis(), QrcodeActivity.class));
                    }
                });
                holder.getView(R.id.terminal_editor).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //编辑
                        Intent intent = new Intent(getThis(), TerminalEditorActivity.class);
                        intent.putExtra("type", "edit");
                        intent.putExtra("shop_id", String.valueOf(dataBean.getShop_id()));
                        intent.putExtra("shop_name", String.valueOf(dataBean.getShop_name()));
                        intent.putExtra("terminal_id", String.valueOf(dataBean.getId()));
                        intent.putExtra("terminal_name", String.valueOf(dataBean.getName()));
                        intent.putExtra("worker_name", String.valueOf(dataBean.getWorkmen_uid()));
                        intent.putExtra("pos_name", String.valueOf(dataBean.getDevice_pos()));
                        intent.putExtra("print_name", String.valueOf(dataBean.getDevice_print()));
                        startActivityForResult(intent, EDITOR_CODE);
                    }
                });
            }
        };
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getThis()));
        mRecyclerView.setAdapter(mCommonAdapter);
    }


    /**
     * 获取终端列表
     */
    private void getTerminalData() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", ApiName.TERMINAL);
        param.add("uid", String.valueOf(PreferenceUtil.getParam(Preferences.UID, "")));
        param.add("login_type", String.valueOf(PreferenceUtil
                .getParam(Preferences.LOGINTYPE, "")));
        param.add("current_page", String.valueOf(pagenum));
        param.add("page_size", String.valueOf(pagesize));
        if ("part".equals(type)) {
            if (!CommonUtil.isEmpty(shopId)) {
                param.add("shop_id", shopId);
            }
            if (!CommonUtil.isEmpty(terminal_name)) {
                param.add("terminal_name", terminal_name);
            }
            if (!CommonUtil.isEmpty(terminal_id)) {
                param.add("terminal_id", terminal_id);
            }
        }
        param.add("sign", param.getMd5String());
        showLoading("加载中");
        HttpUtils.getInstance().url(ApiName.API).params(param)
                .executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissLoading();
                if (CommonUtil.isForeground(getThis())) {
                    showToast(getString(R.string.net_state));
                    String jsonString = ACache.get(App.getApp())
                            .getAsString(ApiName.TERMINAL);
                    if (!CommonUtil.isEmpty(jsonString)) {
                        mBeanList.clear();
                        setTerminalData(jsonString, false);
                    }
                }
                if (mShopListNew.size() == pagesize) {
                    mRefreshLayout.setEnableLoadmore(true);
                } else {
                    mRefreshLayout.setEnableLoadmore(false);
                }
                switch (CURRENT_MODE) {
                    case MODE_QUERY:
                        break;
                    case MODE_REFRESH:
                        mRefreshLayout.finishRefresh(false);
                        break;
                    case MODE_MORE:
                        mRefreshLayout.finishLoadmore(false);
                        break;
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissLoading();
                if (HttpUtils.isJson(string)) {
                    ResponseResult result = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (result.getStatus() == 1) {
                        setTerminalData(string, true);
                    } else {
                        showToast(result.getInfo());
                        mRefreshLayout.setEnableLoadmore(false);
                    }
                } else {
                    mRefreshLayout.setEnableLoadmore(false);
                    showToast(string);
                }

                switch (CURRENT_MODE) {
                    case MODE_QUERY:
                        break;
                    case MODE_REFRESH:
                        mRefreshLayout.finishRefresh(true);
                        break;
                    case MODE_MORE:
                        mRefreshLayout.finishLoadmore(true);
                        break;
                }
                if (mShopListNew.size() == pagesize) {
                    mRefreshLayout.setEnableLoadmore(true);
                } else {
                    mRefreshLayout.setEnableLoadmore(false);
                }

            }
        });
    }

    /**
     * 显示和保存数据
     *
     * @param string
     * @param save
     */
    private void setTerminalData(String string, boolean save) {
        final TerminalData data = GsonUtil.GsonToBean(string, TerminalData.class);
        List<TerminalData.DataBeanX.DataBean> dataBeanList = data.getData().getData();
        mShopListNew = dataBeanList;
        if (CURRENT_MODE != MODE_MORE) {
            mBeanList.clear();
        }
        if (dataBeanList.size() != 0) {
            mBeanList.addAll(dataBeanList);
        } else {
            mRefreshLayout.setEnableLoadmore(false);
        }
        notifyDataRefresh();
        if (save) {
            try {
                String json = GsonUtil.GsonString(mBeanList);
                JSONObject jsonObject = new JSONObject(string);
                JSONObject jsonObject1 = jsonObject.optJSONObject("data");
                JSONArray jsonArray = new JSONArray(json);
                jsonObject1.put("data", jsonArray);
                ACache.get(App.getApp()).put(ApiName.TERMINAL, jsonObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 更新显示数据
     */
    private void notifyDataRefresh() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mCommonAdapter.notifyDataSetChanged();
            }
        });
    }
}
